package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/smash-llj/Nexa-server/global"
	"github.com/smash-llj/Nexa-server/initialize"
	"github.com/spf13/viper"
)

func AppendError(exit, newErr error) error {
	if exit == nil {
		return newErr
	} else {
		return fmt.Errorf("%v,%w", exit, newErr)
	}
}

// Upload 上传文件
func Upload(ctx *gin.Context, fileName string) (string, error) {
	if global.UploadClient == nil {
		initialize.InitUploadClient()
	}
	file, err := ctx.FormFile(fileName)
	if err != nil {
		return "", err
	}
	fileSource, err := file.Open()
	if err != nil {
		return "", err
	}
	defer fileSource.Close()
	name := uuid.New().String() + file.Filename
	_, err = global.UploadClient.Object.Put(ctx, name, fileSource, nil)
	if err != nil {
		return "", err
	}
	fileURL := viper.GetString("UploadBucket.PreviewUrl") + name
	return fileURL, nil
}
